﻿using BW.Mes.WinForms.Common;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BW.Mes.WinForms.WareHouse.CreateStorageForm;
using static BW.Mes.WinForms.WareHouse.SuppliedMaterialsForm;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace BW.Mes.WinForms.WareHouse.ExternalLabel
{
    public partial class CreateExternalLabelForm : DevExpress.XtraEditors.XtraForm
    {
        // 定义委托和事件
        public delegate void ExternalLabelAddedEventHandler(object sender, EventArgs e);
        public event ExternalLabelAddedEventHandler ExternalLabelAdded;

        // 触发事件的方法
        protected virtual void OnExternalLabelAdded()
        {
            ExternalLabelAdded?.Invoke(this, EventArgs.Empty);
        }

        public CreateExternalLabelForm()
        {
            InitializeComponent();

            LoadSuppilerInput();
            InitializeUCheckComboBox();
        }


        private void InitializeUCheckComboBox()
        {
            // 方法1：简单字符串列表
            List<string> separators = new List<string> { "唯一码", "供应商编码", "物料编码", "料号", "数量","批次号","规格","生产日期" };
            uCheckComboBox1.BindingFixedValues(separators);

            // 或者方法2：使用键值对（值和显示文本）
            Dictionary<string, string> separatorDict = new Dictionary<string, string>
    {
        { "唯一码", "唯一码" },
        { "供应商编码", "供应商编码" },
        { "物料编码", "物料编码" },
        { "料号", "料号" },
        { "数量", "数量" },
        { "批次号", "批次号" },
        { "规格", "规格" },
        { "生产日期", "生产日期" },
        
    };
            uCheckComboBox1.BindingFixedValues(separatorDict);

            // 设置默认选中项（如果需要）
            List<string> defaultValues = new List<string> { "唯一码", "供应商编码" };
            uCheckComboBox1.SetSelectedValues(defaultValues);
        }










        private void CreateExternalLabelForm_Load(object sender, EventArgs e)
        {

        }

        

        /// <summary>
        /// 加载供应商信息
        /// </summary>
        private async void LoadSuppilerInput()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    var response = await client.GetAsync("T2/Supplier/GetSupplier");

                    response.EnsureSuccessStatusCode();
                    var responseBody = await response.Content.ReadAsStringAsync();
                    var jsonObject = JsonConvert.DeserializeObject<dynamic>(responseBody);

                    if (jsonObject["pageDatas"] != null)
                    {
                        // 将pageDatas转换为WareHouseItem列表
                        var dataJson = jsonObject["pageDatas"].ToString();
                        var warehouses = JsonConvert.DeserializeObject<List<SuppilerInput>>(dataJson);

                        // 假设您改用了gridLookUpEdit1控件
                        gridLookUpEdit1.Properties.DataSource = warehouses;
                        gridLookUpEdit1.Properties.DisplayMember = "supplierName";
                        gridLookUpEdit1.Properties.ValueMember = "Id";

                        // 配置下拉框，只显示供应商名称
                        gridLookUpEdit1.Properties.View.Columns.Clear();
                        gridLookUpEdit1.Properties.View.Columns.Add(
                            new DevExpress.XtraGrid.Columns.GridColumn
                            {
                                FieldName = "supplierName",
                                Caption = "供应商名称",
                                Visible = true
                            }
                        );

                        // 设置默认提示文本
                        gridLookUpEdit1.Properties.NullText = "请选择供应商";
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载仓库数据失败: {ex.Message}", "错误");
            }
        }



        /// <summary>
        /// 供应商
        /// </summary>
        public class SuppilerInput
        {
            public long Id { get; set; }
            public string supplierName { get; set; }
        }



        /// <summary>
        /// 新增外部标签实体
        /// </summary>
        public class ExternalLabelInput
        {

            public string externalLabelName { get; set; }
            public long supplierId { get; set; }
            public string formats { get; set; }
            public string separator { get; set; }
            public int resolution { get; set; }
            public bool statust { get; set; }
            public string externalLabelDescribe { get; set; }
            /// <summary>
            /// 创建人
            /// </summary>
            public string CreatedBy { get; set; }
        }

        /// <summary>
        /// 确定按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void simpleButton2_Click(object sender, EventArgs e)
        {
            // 表单验证
            if (string.IsNullOrWhiteSpace(textEdit1.Text))
            {
                XtraMessageBox.Show("外部标签名称不能为空", "提示");
                return;
            }
            
            if (string.IsNullOrWhiteSpace(textEdit2.Text))
            {
                XtraMessageBox.Show("分隔符不能为空", "提示");
                return;
            }
            
            if (gridLookUpEdit1.EditValue == null)
            {
                XtraMessageBox.Show("请选择供应商", "提示");
                return;
            }
            
            // 获取选中的分隔符值
            List<string> selectedValues = uCheckComboBox1.GetSelectedValues();
            if (selectedValues.Count == 0)
            {
                XtraMessageBox.Show("请至少选择一个格式项", "提示");
                return;
            }
            
            // 如果需要将多个值组合成一个字符串
            string separator = string.Join(",", selectedValues);
            
            // 使用获取的值创建模型
            var model = new ExternalLabelInput
            {
                externalLabelName = textEdit1.Text,
                separator = textEdit2.Text,
                supplierId = (long)gridLookUpEdit1.EditValue,
                formats = separator, // 使用组合后的分隔符字符串
                statust = toggleSwitch1.IsOn,
                externalLabelDescribe = textEdit3.Text,
                CreatedBy = RequestUser.InputUserName
            };
            
            // 调用 API 方法
            using (var client = new HttpClient())
            {
                //设置请求地址
                client.BaseAddress = new Uri("http://120.26.197.100:8022");
                //创建JSON数据（转换数据类型）
                var json = JsonConvert.SerializeObject(model);
                //创建请求内容
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                //发送POST请求
                var response = await client.PostAsync("T3/Externallabel/CreateExternallabel", content);
                
                //读取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                
                //判断是否成功
                if (response.IsSuccessStatusCode)
                {
                    try
                    {
                        var result = JsonConvert.DeserializeObject<dynamic>(responseContent);
                        
                        // 检查是否包含错误信息
                        if (result != null && result.code != null && result.code.ToString() != "200")
                        {
                            XtraMessageBox.Show($"保存失败: {result.message}", "错误");
                            return;
                        }
                        
                        // 成功
                        XtraMessageBox.Show("保存成功");
                        
                        // 触发事件通知父窗体刷新数据
                        OnExternalLabelAdded();
                        
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    catch
                    {
                        XtraMessageBox.Show("保存成功");
                        OnExternalLabelAdded();
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                }
                else
                {
                    try
                    {
                        var result = JsonConvert.DeserializeObject<dynamic>(responseContent);
                        if (result != null && result.message != null)
                        {
                            XtraMessageBox.Show($"保存失败: {result.message}", "错误");
                        }
                        else
                        {
                            XtraMessageBox.Show("保存失败:" + response.ReasonPhrase, "错误");
                        }
                    }
                    catch
                    {
                        XtraMessageBox.Show("保存失败:" + response.ReasonPhrase, "错误");
                    }
                }
            }
        }

        /// <summary>
        /// 取消按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}